package com.qiusuo0226.platform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiusuo0226.common.util.SystemTool;
import com.qiusuo0226.file.util.DownloadUtil;
import com.qiusuo0226.file.util.FileResource;
import com.qiusuo0226.file.util.MultipartFileTool;
import com.qiusuo0226.platform.mapper.FileStoreMapper;
import com.qiusuo0226.platform.pojo.po.FileStorePO;
import com.qiusuo0226.platform.service.FileStoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件仓库数据处理层
 * @author qiusuo
 * @date 2023/7/7 22:09
 */
@Service
@Slf4j
public class FileStoreServiceImpl extends ServiceImpl<FileStoreMapper, FileStorePO> implements FileStoreService {


    @Override
    public Long add(MultipartFile file) {
        FileStorePO entity = new FileStorePO();
        entity.setSize(file.getSize());
        entity.setName(file.getOriginalFilename());
        entity.setSuffix(MultipartFileTool.getSuffix(file));
        try {
            entity.setData(file.getBytes());
        } catch (IOException e) {
            log.error("上传文件获取字节流异常", e);
            throw new RuntimeException("上传文件获取字节流异常", e);
        }

        int insert = baseMapper.insert(entity);
        if (insert > 0) {
            // 新增文件成功
            return entity.getIid();
        } else {
            // 新增文件失败
            return null;
        }
    }

    @Override
    public FileResource export(long iid) {
        FileStorePO entity = baseMapper.selectById(iid);
        File file = new File(SystemTool.getProjectPath() + File.separator + entity.getName());
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(entity.getData());
        } catch (IOException e) {
            log.error("二进制流转文件异常", e);
        }
        return DownloadUtil.getFileResource(file, entity.getName(), true);
    }
}
